package com.ylkj.patient.rnmodule;


import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableMap;
import com.google.gson.Gson;
import com.users.rn.kit.bridge.impl.net.KitNetworkModule;
import com.examination.mlib.interfaceapi.NetWorkCallBack;
import com.examination.mlib.interfaceapi.UpLoadCallBack;
import com.users.rn.rncommon.util.ReactUtils;
import com.yilijk.base.AppBase;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.oss.UploadOssUtils;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.ToastUtils;
import com.ylkj.patient.utils.AppReactUtils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**

 * 作者：wolf on 12/28/20 16:47

 * 邮箱：bluce

 */

public class RNNetworkModule extends KitNetworkModule {
    String requestBody = null;
    RequestBody body = null;
    Call<ResponseBody> netWorkJson = null;
    Gson gson = new Gson();


    /**
     * 网络请求
     * @param reactContext
     * @param domin 域名
     * @param methodName 请求字段
     * @param type 请求类型
     * @param params 接受数据
     * @param promise 回调
     */


    @Override
    public void requestNet(@NotNull ReactContext reactContext, @NotNull String domin, @NotNull String methodName, @NotNull String type,@NotNull boolean isLoading, @NotNull ReadableMap params, @NotNull Promise promise) {

        /**
         * log 打印接受数据
         */
        CommonUtils.loginfo("Android accept domim:" + domin+methodName);
        CommonUtils.loginfo("Android accept type:" + type);
        CommonUtils.loginfo("Android accept params:" + params);
        CommonUtils.loginfo("Android accept params:" + isLoading);
//        if (ProjectConfigure.isAndroidDomin) {
        if (true) {
            if (!methodName.startsWith("http") && !methodName.startsWith("https")){
                if (methodName.startsWith("/")){
                    domin = HttpUtils.getUrl();
                }else{
                    domin = HttpUtils.getUrl()+"/";
                }
            }
        }

        boolean isOss = true;
//        if (params.hasKey("isOss")){
//            isOss = params.getBoolean("isOss");
//        }
        String requestJson = "";
        JSONObject paramsJSON = AppReactUtils.INSTANCE.getPramasJSONObject(params.toString());
        RequestParams requestParams = null;
        try {
            if (paramsJSON.has("NativeMap")){
                requestJson = paramsJSON.getString("NativeMap");
            }else{
                requestJson = paramsJSON.toString();
            }
            requestParams = new RequestParams(requestJson);
            if (reactContext != null && reactContext.getCurrentActivity() != null) {
                Activity context = reactContext.getCurrentActivity();
                Intent intent = context.getIntent();
                String module = intent.getStringExtra("intent_key_plugin_id");
//                modulePage.append("_").append(intent.getStringExtra("intent_key_module_id"));
                String modulePage = intent.getStringExtra("intent_key_component_name");
                if (!TextUtils.isEmpty(module)) {
                    requestParams.put("module", module);
                }
                if (!TextUtils.isEmpty(modulePage)) {
                    requestParams.put("modulePage", modulePage);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /**
         * 判断POST/GET请求
         *
         */
        if (type.equals("POST")){
            HttpUtils.post(methodName, requestParams, new HttpCallBack<String>() {
                @Override
                public void onSuccess(String s, int i) {
                    promise.resolve(s);
                }

                @Override
                public void onFailure(String s, int i) {
                    promise.resolve(s);
                }
            });
        }
        else if (type.equals("GET")){
            HttpUtils.get(methodName, requestParams, new HttpCallBack<String>() {
                @Override
                public void onSuccess(String s, int i) {
                    promise.resolve(s);

                }

                @Override
                public void onFailure(String s, int i) {
                    promise.resolve(s);
                }
            });
        }
        else if (type.equals("UPLOAD")){
            String filePath = null;
            if (params.hasKey("filePath")) {
                try {
                    filePath = params.getString("filePath");
                } catch (Exception e) {
                }
            }
            if (TextUtils.isEmpty(filePath)){
                RequestParams exceptionParams = new RequestParams();
                exceptionParams.put("result", false);
                exceptionParams.put("status", 0);
                exceptionParams.put("data", "");
                exceptionParams.put("msg", "请选择标准图片进行上传");
                promise.resolve(exceptionParams.toString());
                return;
            }
            String uri2Path = null;
            File file = null;
            if (filePath.charAt(0) != '/') {
                uri2Path = CommonUtils.getModuleCommonUtils().Uri2Path(AppBase.getApplication(), filePath);
            } else {
                uri2Path = filePath;
            }
            file = new File(uri2Path);
            if (isOss) {
                //如果上传成功的路径
                if (UploadOssUtils.getInstance().getData() == null || UploadOssUtils.getInstance().getData().getStartWith() == null){
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("result", false);
                        jsonObject.put("msg", "Oss上传信息过期");
                        jsonObject.put("message", "Oss上传信息过期");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    promise.resolve(jsonObject.toString());
                    return;
                }
                String ossPath = UploadOssUtils.getInstance().getData().getStartWith() + "android/patient/image/" + file.getName().replace("_", "");
                HttpUtils.uploadFile2Oss(file, new HttpCallBack<String>() {
                    @Override
                    public void onSuccess(String result, int code) {
                        RequestParams upLoadResult = new RequestParams();
                        upLoadResult.put("result", true);
                        upLoadResult.put("status", 200);
                        upLoadResult.put("data", "https://imageserver.yilijk.com/" + ossPath);
                        upLoadResult.put("ossKey",UploadOssUtils.getInstance().getData().getAccessKeyId());
                        promise.resolve(upLoadResult.toString());
                    }

                    @Override
                    public void onFailure(String failureMsg, int statusCode) {
                        UploadOssUtils.getInstance().init();
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("result", false);
                            jsonObject.put("msg", failureMsg);
                            jsonObject.put("message", failureMsg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        promise.resolve(jsonObject.toString());
                    }
                });
            } else {
                HttpUtils.uploadFile(domin + methodName, new RequestParams(), filePath, new HttpCallBack<String>() {
                    @Override
                    public void onSuccess(String result, int code) {
                        promise.resolve(result);
                    }

                    @Override
                    public void onFailure(String failureMsg, int statusCode) {
                        promise.resolve(failureMsg);
                    }
                });
            }
        }
        else if(type.equals("UPLOADFILE")){
            String filePath = null;
            if (params.hasKey("filePath")) {
                try {
                    filePath = params.getString("filePath");
                } catch (Exception e) {
                }
            }
            if (TextUtils.isEmpty(filePath)){
                RequestParams exceptionParams = new RequestParams();
                exceptionParams.put("result", false);
                exceptionParams.put("status", 0);
                exceptionParams.put("data", "");
                exceptionParams.put("msg", "请选择标准图片进行上传");
                promise.resolve(exceptionParams.toString());
                return;
            }
            File file = null;
            file = new File(filePath);
            if (!file.exists()) {
                ToastUtils.showShort("文件不存在");
                return;
            }

            if (isOss) {
                //如果上传成功的路径
                if (UploadOssUtils.getInstance().getData() == null || UploadOssUtils.getInstance().getData().getStartWith() == null){
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("result", false);
                        jsonObject.put("msg", "Oss上传信息过期");
                        jsonObject.put("message", "Oss上传信息过期");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    promise.resolve(jsonObject.toString());
                    return;
                }
                String s = UploadOssUtils.getInstance().getData().getStartWith() + "android/patient/file/" + file.getName().replace("_", "");
                HttpUtils.uploadAmr2Oss(file, new HttpCallBack<String>() {
                    @Override
                    public void onSuccess(String result, int code) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("result", true);
                            jsonObject.put("status", 200);
                            jsonObject.put("data", "https://imageserver.yilijk.com/" + s);
                            jsonObject.put("ossKey",UploadOssUtils.getInstance().getData().getAccessKeyId());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        promise.resolve(jsonObject.toString());
                    }

                    @Override
                    public void onFailure(String failureMsg, int statusCode) {
                        UploadOssUtils.getInstance().init();
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("result", true);
                            jsonObject.put("msg", failureMsg);
                            jsonObject.put("message", failureMsg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        promise.resolve(jsonObject.toString());
                    }
                });
            } else {
                HttpUtils.uploadAmr(domin + methodName, file, new HttpCallBack<String>() {
                    @Override
                    public void onSuccess(String result, int code) {
                        promise.resolve(result);
                    }

                    @Override
                    public void onFailure(String failureMsg, int statusCode) {
                        promise.resolve(failureMsg);
                    }
                });
            }
        }
    }


}